<template>
  <div class="wrapper">
    <!-- header部分 -->
    <button class="back-arrow" @click="goBack"></button>
    <header class="header">
      <p>用户注册</p>
    </header>
    <!-- 表单部分 -->
    <ul class="form-box">
      <li class="form-item">
        <div class="title">
          手机号码：
        </div>
        <div class="content">
          <input type="text" @blur="checkUserId" v-model="user.userId" placeholder="手机号码">
        </div>
      </li>
      <li class="form-item">
        <div class="title">
          密码：
        </div>
        <div class="content">
          <input type="password" v-model="user.password" placeholder="密码" @input="checkPasswordStrength">
          <div class="password-strength" :style="{ backgroundColor: passwordStrengthColor }"></div>
        </div>
      </li>
      <li class="form-item">
        <div class="title">
          确认密码：
        </div>
        <div class="content">
          <input type="password" v-model="confirmPassword" placeholder="确认密码">
        </div>
      </li>
      <li class="form-item">
        <div class="title">
          用户名称：
        </div>
        <div class="content">
          <input type="text" v-model="user.userName" placeholder="用户名称">
        </div>
      </li>
      <li class="form-item">
        <div class="title">
          性别：
       </div>
               <div class="content" style="font-size: 3vw;">
                 <input type="radio" v-model="user.userSex" value="1" id="male" style="width:6vw;height: 3.2vw;">
                 <label for="male" style="margin-right: 1vw;">男</label>
                 <input type="radio" v-model="user.userSex" value="0" id="female" style="width:6vw;height: 3.2vw;">
                 <label for="female">女</label>
               </div>
             </li>
             <li class="form-item">
               <div class="title">
          上传头像：
        </div>
        <div class="content">
          <input type="file" @change="handleFileChange" accept="image/png">
        </div>
      </li>
    </ul>
    <div class="button-login">
      <button @click="register">注册</button>
    </div>
     <!-- Alert Modal -->
     <alert-modal v-if="alertVisible" :visible.sync="alertVisible" :message="alertMessage"></alert-modal>
    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script>
import Footer from '../components/Footer.vue';
import AlertModal from '../views/AlertModal.vue';
import JSEncrypt from 'jsencrypt';
import request from '../request.js';
export default {
  name: 'Register',
  data() {
    return {
      user: {
        userId: '',
        password: '',
        userName: '',
        userSex: 1,
        userImg: '', // 添加这个属性
      },
      PublicKey: '' , // 公钥
      confirmPassword: '',
      passwordStrengthColor: '#ccc', // 默认颜色
      alertVisible: false,
		  alertMessage: ''
    };
  },
  methods: {
    goBack() {
		console.log('Trying to go back...');
		this.$router.go(-1); // 相当于浏览器的后退操作
	  },
    checkUserId() {
      const regex = /^1(3\d|4[5-9]|5[0-35-9]|6[5-7]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      if (!regex.test(this.user.userId)) {
				  this.alertMessage ='手机号码格式不正确!';
				  this.alertVisible = true;
				  return;
			}
      this.$axios.post(`users/${this.user.userId}`).then(response => {
        if (response.data===1) {
          this.user.userId = '';
         this.alertMessage ='此手机号码已存在！';
         this.alertVisible = true;
        }
        else this.PublicKey = response.data;
      }).catch(error => {
        console.error(error);
      });
    },
    compressImage(file, maxSize) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = (e) => {
            const img = new Image();
            img.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              const maxSizeMB = maxSize / 1024 / 1024; // 将KB转换为MB
              const width = img.width;
              const height = img.height;
    
              // 设置canvas大小
              canvas.width = width;
              canvas.height = height;
    
              // 压缩图片
              ctx.drawImage(img, 0, 0, width, height);
              const dataUrl = canvas.toDataURL('image/jpeg', 0.6); // 质量参数可以调整
              const blob = dataURLToBlob(dataUrl);
    
              // 创建新的File对象
              const newFile = new File([blob], file.name, { type: 'image/jpeg', lastModified: Date.now() });
              if (newFile.size <= maxSize) {
                resolve(newFile);
              } else {
                reject('Image compression did not reduce the file size enough.');
              }
            };
            img.onerror = (error) => {
              reject(error);
            };
            img.src = e.target.result;
          };
          reader.onerror = (error) => {
            reject(error);
          };
          reader.readAsDataURL(file);
        });
      },
      handleFileChange(event) {
        const file = event.target.files[0];
        if (file) {
          this.compressImage(file, 350 * 1024) // 350KB
            .then((compressedFile) => {
              const reader = new FileReader();
              reader.onload = (e) => {
                this.user.userImg = e.target.result;
              };
              reader.readAsDataURL(compressedFile);
            })
            .catch((error) => {
              console.error('Error compressing image:', error);
              this.alertMessage = 'Error compressing image.';
              this.alertVisible = true;
            });
        }
      },
    checkPasswordStrength() {
      const strength = this.getPasswordStrength(this.user.password);
      switch (strength) {
        case 0:
          this.passwordStrengthColor = 'red';
          break;
        case 1:
          this.passwordStrengthColor = 'red';
          break;
        case 2:
          this.passwordStrengthColor = 'yellow';
          break;
		case 3:
		  this.passwordStrengthColor = 'yellow';
		  break;
		case 4:
		  this.passwordStrengthColor = 'green';
		  break;  
		case 5:
		  this.passwordStrengthColor = 'green';
		  break;
      }
    },
    getPasswordStrength(password) {
      let strength = 0;
      if (password.length > 5) strength++;
      if (password.match(/[a-z]/)) strength++;
      if (password.match(/[A-Z]/)) strength++;
      if (password.match(/[0-9]/)) strength++;
      if (password.match(/[\W_]/)) strength++;
      return strength;
    },
    register() {
      if (this.user.userId == '') {
       this.alertMessage ='手机号码不能为空！';
       this.alertVisible = true;
        return;
      }
      if (this.user.password == '') {
        this.alertMessage ='密码不能为空！';
        this.alertVisible = true;
        return;
      }
      if (this.user.password != this.confirmPassword) {
        this.alertMessage ='两次输入的密码不一致！';
        this.alertVisible = true;
        return;
      }
      if (this.user.userName == '') {
        this.alertMessage ='用户名不能为空！';
        this.alertVisible = true;
        return;
      }

      const encryptor = new JSEncrypt()
      encryptor.setPublicKey(this.PublicKey)  // 放入公钥
      let passwordAfterEncrypt = encryptor.encrypt(this.user.password)  // 加密密码 

      // 注册请求，包括图像数据
      this.$axios.post('users/', this.$qs.stringify({
        userId: this.user.userId,
        password: passwordAfterEncrypt,
        userName: this.user.userName,
        userSex: this.user.userSex,
        userImg: this.user.userImg // 确保图像数据被发送
      })).then(response => {
        if (response.data > 0) {
          this.alertMessage ='注册成功！';
          this.alertVisible = true;
          this.$router.go(-1);
        } else {
         this.alertMessage ='注册失败！';
         this.alertVisible = true;
        }
      }).catch(error => {
        console.error(error);
      });
    }
  },
  components: {
    Footer,AlertModal
  }
}
function dataURLToBlob(dataUrl) {
  const byteString = atob(dataUrl.split(',')[1]);
  const mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
}
</script>

<style scoped>
  /****************** 总容器 ******************/
  .wrapper {
    width: 100%;
    min-height: 100vh;
    background-color: white;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 6rem; /* 增加内边距以避免内容被固定头部覆盖 */
    box-sizing: border-box;
    position: relative;
  }
 /****************** 返回键 ******************/
 
.back-arrow {
  position: fixed; /* 固定定位 */
  left: 2.5vw; /* 距离屏幕左端像素 */
  top: 2.5vw; /* 距离屏幕顶部像素 */
  width: 8vw; /* 使用视口宽度的百分比 */
  height: 8vw; /* 使用视口宽度的百分比，保持宽高比 */
  background-color: rgba(0, 151, 255, 0.5); /* 半透明的背景颜色 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border: none; /* 隐藏边框 */
  transition: background-color 0.3s ease; /* 背景颜色变化动画 */
}

.back-arrow::before {
  content: '\f053'; /* 使用 FontAwesome 的左箭头图标 */
  font-family: 'FontAwesome'; /* FontAwesome 字体 */
  font-size: 5vh; /* 使用视口高度的百分比，确保在不同设备上也合适 */
  color: #fff; /* 字体颜色 */
  transition: color 0.3s ease; /* 字体颜色变化动画 */
}

.back-arrow:hover::before {
  color: #0a2ddc; /* 鼠标悬停时的颜色变化 */
}

.back-arrow:hover {
  background-color: rgba(0, 151, 255, 0.3); /* 鼠标悬停时的背景颜色变化为更透明 */
}
  /****************** 表单部分 ******************/
  .form-box {
    width: calc(100% - 4rem);
    max-width: 480px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
    padding: 2rem;
    box-sizing: border-box;
  }

  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 1rem;
  }

  .title {
    flex: 1;
    font-size: 1.2rem;
    color: #333;
  }

  .content {
    flex: 2;
  }

  .content input {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    transition: border-color 0.3s, box-shadow 0.3s;
  }

  .content input:focus {
    border-color: #2575fc;
    box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.5);
    outline: none;
  }

  .password-strength {
    height: 4px;
    width: 100%;
    border-radius: 4px;
    margin-top: 0.5rem;
  }

  .button-login {
    margin-top: 1.5rem;
  }

  .button-login button {
    width: 100%;
    padding: 0.75rem;
    font-size: 1.1rem;
    color: white;
    background-color: #38CA73;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
  }

  .button-login button:hover {
    background-color: #2f995b;
  }

  .button-login button:active {
    transform: scale(0.98);
  }

  /** 底部菜单部分 **/
  Footer {
    margin-top: auto;
  }
  .content input[type="file"] {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 1rem;
    transition: border-color 0.3s, box-shadow 0.3s;
  }
  
  .content input[type="file"]:focus {
    border-color: #2575fc;
    box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.5);
    outline: none;
  }
</style>